//
//  LoginViewModel.swift
//  mmda
//
//  Created by 李陆涛 on 2018/4/24.
//  Copyright © 2018年 mmda. All rights reserved.
//

import UIKit
import RxSwift

enum InputType {
    case mobile
    case code
}

struct RegexHelper {
    
    let regex: NSRegularExpression?
    
    init(_ pattern: String) {
        
        do {
            regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
        } catch  {
            regex = nil
        }
    }
    
    func match(_ input: String) -> Bool {
        
        let len = input.count
        let range = NSMakeRange(0, len)
        
        if let matches = regex?.matches(in: input, options: NSRegularExpression.MatchingOptions.reportProgress, range: range) {
            
            return matches.count > 0
        } else {
            
            return false
        }
    }
    
}


class LoginViewModel: NSObject {
    
    var loginSuccess:((String?)->Void)?
    
    //    手机号
    let mobile = Variable("")
    //    验证码
    let code = Variable("")
    
    //    显示信息
    let message = Variable("")
    //    显示正在加载
    let showLoading = Variable(false)
    
    //    倒计时剩余时间
    private let leftTime = Variable(TimeInterval(61))
    //    当前倒计时是否结束
    private let timeStopped = Variable(false)
    
    
    //    手机号是否正确
    let mobileValid: Observable<Bool>
    //    获取验证码是否可用
    let getCodeValid: Observable<(Bool,Int)>
    //    登录按钮是否可用
    let everythingValid: Observable<Bool>
    
    
    override init() {
        
        
        mobileValid = mobile.asObservable().map { text -> Bool in
            
            let pattern = "^1[0-9]{10}$"
            let matcher = RegexHelper(pattern)
            
            return matcher.match(text)
            }.share(replay: 1)
        
        let codeValid = code.asObservable().map { text -> Bool in
            
            let pattern = "^[0-9]{4,6}$"
            let matcher = RegexHelper(pattern)
            
            return matcher.match(text)
            }.share(replay: 1)
        
        let btnTag = leftTime.asObservable().map({ tag -> Int in
            
            return Int(tag)
        })
        
        getCodeValid = Observable.combineLatest(mobileValid,btnTag) {
            enable, tag in
            
            if (enable && (tag >= 60)) {
                
                return (true,tag)
            }
            
            return (false, tag)
            
            }.share(replay: 1)
        
        everythingValid = Observable.combineLatest(mobileValid,codeValid) {$0 && $1}.share(replay: 1)
        
    }
    
    /// 获取验证码
    func getCode() {
        
        let mobile = self.mobile.value
        
        NetAPI.code(mobile: mobile).request {
            
            [weak self] response, errmsg in
            guard let `self` = self else { return }
            
            guard let msg = errmsg else {
                
                self.message.value = "发送成功"
                return
            }
            
            self.timeStopped.value = true
            self.leftTime.value = 60
            
            self.message.value = msg
        }
        
        self.leftTime.value = 59
        
        Observable<Int>.interval(1, scheduler: MainScheduler.instance)
            .takeUntil(timeStopped.asObservable().filter{$0})
            .subscribe{
                
                [weak self] event in
                guard let `self` = self else { return }
                
                self.leftTime.value -= 1
                
                if self.leftTime.value == 0 {
                    
                    self.timeStopped.value = true
                    self.leftTime.value = 60
                }
            }.disposed(by: disposeBag)
        
    }
    
    
    /// 登录
    func login() {
        
        
        self.showLoading.value = true
        
        let mobile = self.mobile.value
        let code = self.code.value
        
        
        NetAPI.checkcode(mobile: mobile, code: code).request {
            
            [weak self] response, errmsg in
            guard let `self` = self else { return }
            
            self.showLoading.value = false
            guard let res = response as? [String:Any] else {
                
                self.message.value = errmsg ?? "未知错误"
                
                self.loginSuccess?(errmsg ?? "未知错误")
                
                return
            }
            
            
            AppManager.share.token = res["token"] as? String
            AppManager.share.mobile = mobile
            AppManager.share.code = code

            self.loginSuccess?(nil)
            
        }
    }
    
    //    aggrement
    var aggrementLabelType = ActiveType.custom(pattern: "\\萌萌哒用户使用协议\\b")
    var aggrementLAbelAttr:((ActiveType,[NSAttributedStringKey:Any],Bool) -> [NSAttributedStringKey : Any]) = { (type, attributes, isSelected) in
        
        var atts = attributes
        
        atts[NSAttributedStringKey.underlineStyle] = 1
        
        return atts
    }
    
    var aggrementURL:String? {
        
        return AppManager.share.appModel?.app_agreement?.url
    }
    
    var aggrementTitle:String? {
        
        return AppManager.share.appModel?.app_agreement?.title
    }
    
    //
    
    
    
}



